package com.jia.together.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jia.together.entity.Course;
import com.jia.together.entity.CourseType;
import com.jia.together.entity.CourseType;
import com.jia.together.mapper.CourseTypeMapper;
import com.jia.together.service.CourseService;
import com.jia.together.service.CourseTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jia.together.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dujiajia
 * @since 2021-02-20
 */
@Service
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements CourseTypeService {

    @Autowired
    private CourseService courseService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Map<String, Object> selectPageList(Long pageNum, Long pageSize) {

        Page<CourseType> page = new Page<>(pageNum, pageSize);
        QueryWrapper<CourseType> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("gmt_create");
        Page<CourseType> resourcePage = baseMapper.selectPage(page, wrapper);
        List<CourseType> records = resourcePage.getRecords();
        long total = resourcePage.getTotal();
        Map<String, Object> map = new HashMap<>();
        map.put("records", records);
        map.put("total", total);
        return map;

    }

    @Override
    public List<CourseType> selectCourseList() {
        Object courseTypesRedis = redisUtil.get("courseTypes");
        if (courseTypesRedis == null){
            QueryWrapper<CourseType> wrapper = new QueryWrapper<>();
            wrapper.orderByAsc("sort");
            List<CourseType> courseTypes = baseMapper.selectList(wrapper);
            courseTypes.forEach(item->{
                Map<String, Object> map = courseService.selectPageList(item.getId(), 1L, 8L);
                List<Course> records = (List<Course>) map.get("records");
                records.forEach(course -> {
                    redisUtil.set(course.getId() + "_course_views",course.getViews());
                });
                item.setCourses(records);
            });
            redisUtil.set("courseTypes",courseTypes,60*60);
            return courseTypes;
        }
        return (List<CourseType>) courseTypesRedis;
    }
}
